import json

import pandas as pd
import torch
from django.core import serializers
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_http_methods

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt  # 如果需要禁用 CSRF 验证
from torch.utils.data import DataLoader

from TabularCNP.cDeepFM import CDeepFM, CDeepFM_predict
from TabularCNP.dataloader import cWDLDataset
from backend.models import CD

@csrf_exempt
def handle_data(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            print("Received data:", data)

            [listing_year, listing_month, listing_day] = data['listingDate'].split('-');

            if data['elevatorAvailable'] == 0:
                elevatoravailable = True
            elif data['elevatorAvailable'] == 1:
                elevatoravailable = False
            else:
                elevatoravailable = None  # 或者其他默认值

            print(elevatoravailable)
            print(1)
            # cd = CD(
            #     longitude=data['longitude'],
            #     latitude=data['latitude'],
            #     building_area=data['buildingArea'],
            #     total_floors=data['totalFloors'],
            #     listing_price=data['listingPrice'],
            #     year_built=data['yearBuilt'],
            #     price_adjustment=data['priceAdjustment'],
            #     viewing_count=data['viewingCount'],
            #     followers_count=data['followersCount'],
            #     visitors_count=data['visitorsCount'],
            #     ladders=data['ladders'],
            #     houses=data['houses'],
            #     kitchens=data['kitchens'],
            #     bedrooms=data['bedrooms'],
            #     living_rooms=data['livingrooms'],
            #     bathrooms=data['bathrooms'],
            #     listing_year=listing_year,
            #     listing_month=listing_month,
            #     listing_day=listing_day,
            #     # 这些数据可能需要学长处理一下……
            #     # 字符串（汉字）——可能需要学长转到您那边的编号
            #     district_name=data['districtName'],
            #     business_area = data['businessArea'],
            #     community_name = data['communityName'],
            #     heating_method = data['heatingMethod'],
            #     house_usage = data['houseUsage'],
            #     # 索引——我们两边可能需要统一一下这个索引所代表的什么……学长您把每个内容所代表的编号给我我们跟着您的改前端就好！
            #     apartment_type = data['apartmentType'],
            #     building_type = data['buildingType'],
            #     house_orientation = data['houseOrientation'],
            #     renovation_status = data['renovationStatus'],
            #     building_structure = data['buildingStructure'],
            #     house_ownership = data['houseOwnership'],
            #     transaction_rights = data['transactionRights'],
            #     elevator_available=elevatoravailable,  # 从表单获取布尔值
            #     house_age=data['house_age'],
            # )

            #类别变量字典
            with open('E:\\postgraduate\\testDC24First\\TabularCNP\\sparse_feature_encodings.json', 'r',
                      encoding='utf-8') as f:
                query_dict = json.load(f)
            print(query_dict)

            #整体数据集
            cd = CD.objects.all().values()
            cd_data = pd.DataFrame(cd)

            #测试数据样本
            test_data = CD(
                longitude=104.103673,
                latitude=30.60889,
                building_area=54,
                total_floors=11,
                listing_price=74,
                year_built=2010,
                price_adjustment=1,
                viewing_count=7,
                followers_count=31,
                visitors_count=2409,
                ladders=1,
                houses=4,
                kitchens=1,
                bedrooms=1,
                living_rooms=1,
                bathrooms=1,
                listing_year=2021,
                listing_month=1,
                listing_day=1,
                district_name=2,
                business_area=59,
                community_name=1968,
                apartment_type=1,
                building_type=1,
                house_orientation=1,
                renovation_status=3,
                building_structure=2,
                heating_method=0,
                elevator_available=0,
                transaction_rights=0,
                house_usage=0,
                house_age=1,
                house_ownership=1,
            )
            data_dict = test_data.__dict__
            cd_test = pd.DataFrame([data_dict])
            print(cd_test)
            #预测
            prediction = CDeepFM_predict(cd_test, cd_data)

            # 假设计算了成交均价和成交周期
            transaction_avg_price = prediction #预测结果
            transaction_cycle = 30#目前模型是单输出模型，暂不预测成交周期

            # 返回成功响应
            return JsonResponse({
                'status':'success',
                'transactionAvgPrice': transaction_avg_price,
                'transactionCycle': transaction_cycle
            })
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)})
    else:
        return JsonResponse({'status': 'error', 'message': 'Invalid request method'})